package algorithm;

import java.util.concurrent.LinkedBlockingQueue;

public class ThreadPrintDemo2 {

  public static void main(String[] args) {

    ThreadPrintDemo2 threadPrintDemo2 = new ThreadPrintDemo2();
    threadPrintDemo2.doWork();

  }

  public void doWork() {

    int count = 3;

    LinkedBlockingQueue<Integer> Asyn = new LinkedBlockingQueue<>();
    LinkedBlockingQueue<Integer> Bsyn = new LinkedBlockingQueue<>();
    LinkedBlockingQueue<Integer> Csyn = new LinkedBlockingQueue<>();
    PrintWork A = new PrintWork(Asyn, Bsyn, "A", 3);
    PrintWork B = new PrintWork(Bsyn, Csyn, "B", 3);
    PrintWork C = new PrintWork(Csyn, Asyn, "C", 3);

    new Thread(A).start();
    new Thread(B).start();
    new Thread(C).start();

    System.out.println("start ...");
    Asyn.add(1);

  }

  static class PrintWork implements Runnable {

    private LinkedBlockingQueue<Integer> nextSyn = new LinkedBlockingQueue<>();

    private LinkedBlockingQueue<Integer> syn = new LinkedBlockingQueue<>();

    private String print;

    private int count;

    public PrintWork(LinkedBlockingQueue<Integer> syn, LinkedBlockingQueue<Integer> nextSyn, String print, int count) {
      this.syn = syn;
      this.nextSyn = nextSyn;
      this.print = print;
      this.count = count;
    }

    @Override
    public void run() {

      try {
        for (int i = 0; i < this.count; i++) {
          Integer take = this.syn.take();
          //打印
          System.out.println(print);
          this.nextSyn.add(take);
        }

      } catch (InterruptedException e) {
        e.printStackTrace();
      }

    }

  }

}
